import { useEffect, useRef, useState } from "react";
import FilterCard from "@/pages/components/FilterCard/index";
import TableCard from "./components/TableCard";
import { getCourse, getTeacherTitle } from "../common";
import { getTeacherListApi } from "@/api/school/teacher";
import type { FilterCardRefType, FilterFormItemType, ValueType } from "@/pages/components/FilterCard/types/index.type";
import type { TableDataType } from "./types/tableCard.type";
import type { TabelPropsType } from "./types/index.type";

const filterFormList: FilterFormItemType[] = [
  { label: "教师姓名", name: "teacherName", type: "input" },
  { label: "教师职称", name: "teacherTitle", type: "select", options: getTeacherTitle() },
  { label: "负责课程", name: "course", type: "select", options: getCourse() },
];

const Teacher = () => {
  const filterCardRef = useRef<FilterCardRefType>(null);
  const [tabelData, setTabelData] = useState<TableDataType[]>([]);
  const [isLoading, setLoading] = useState(false);
  const [pages, setPages] = useState({ pageNum: 1, pageSize: 10, total: 0 });
  // 表格 props
  const tableProps: TabelPropsType = {
    loading: isLoading,
    pagination: {
      pageSize: pages.pageSize,
      total: pages.total,
      showQuickJumper: true,
      showSizeChanger: true,
      showTotal: () => <div>总条数：{pages.total}条</div>,
      onShowSizeChange: onPaginationChange,
      onChange: onPaginationChange,
    },
  };

  const getListData = async (filterParams?: { [key: string]: string }) => {
    setLoading(true);
    try {
      let params = { pageNum: pages.pageNum, pageSize: pages.pageSize };
      filterParams && (params = { ...params, ...filterParams });
      const { data } = await getTeacherListApi<typeof params, { total: number; rows: TableDataType[] }>(params);
      setTabelData(data.rows);
      setPages(prev => ({ ...prev, total: data.total }));
    } finally {
      setLoading(false);
    }
  };
  // 分页
  function onPaginationChange(pageNum: number, pageSize: number) {
    setPages(prev => ({ ...prev, pageNum, pageSize }));
  }
  const onFilterCardFinish = (value: ValueType) => {
    getListData(value);
  };
  const onReset = () => {
    filterCardRef.current?.onReset();
    getListData();
  };

  useEffect(() => {
    getListData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pages.pageNum, pages.pageSize]);

  return (
    <div>
      <FilterCard
        ref={filterCardRef}
        filterFormList={filterFormList}
        onFinish={onFilterCardFinish}
        onReset={getListData}
      />
      <TableCard tableProps={tableProps} tabelData={tabelData} onReset={onReset} />
    </div>
  );
};

export default Teacher;
